/*
 *  Copyright (C) 2011 glauco
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.balisunrise.swing.builders;

import javax.swing.JPanel;
import org.balisunrise.annotation.EventType;
import org.balisunrise.annotation.VisualActionTarget;
import org.balisunrise.annotation.util.AnnotationsUtilitiesException;
import org.balisunrise.annotation.util.NameUtil;
import org.balisunrise.annotation.util.SearchUtilities;
import org.balisunrise.application.Application;
import org.balisunrise.builder.BuilderException;
import org.balisunrise.builder.CommonFactory;
import org.balisunrise.builder.FactoryException;
import org.balisunrise.common.Action;
import org.balisunrise.common.ActionProvider;
import org.balisunrise.common.EntityActions;
import org.balisunrise.common.EntityFilter;
import org.balisunrise.common.EntityGrid;
import org.balisunrise.common.EntityList;
import org.balisunrise.common.EntityLoader;
import org.balisunrise.common.Search;
import org.balisunrise.common.VisualAction;
import org.balisunrise.swing.commons.listeners.EntityActionsListener;
import org.balisunrise.swing.commons.listeners.EntityLoadListener;
import org.balisunrise.swing.components.panel.SearchPanel;
import org.balisunrise.swing.components.panel.layouts.SearchLayoutBuilder;

/**
 *
 * @author glauco
 */
public class SearchBuilder implements org.balisunrise.builder.SearchBuilder {

    private static final String MESSAGE = "Erro ao construir uma Search.\n";

    @Override
    public Search create(Class entityClass, String alias)
            throws BuilderException {

        if(entityClass == null){
            throw new BuilderException(MESSAGE +
                    "entityClass não pode ser nulo.");
        }

        if(alias == null){
            throw new BuilderException(MESSAGE +
                    "alias não pode ser nulo.");
        }

        try{
            SearchUtilities su = SearchUtilities.create(entityClass, alias);
            return create(su);
        }catch(AnnotationsUtilitiesException aue){
            throw new BuilderException(MESSAGE +
                    aue.getMessage(), aue.getCause());
        }
    }

    @Override
    public Search create(SearchUtilities su) throws BuilderException {

        if(su == null){
            throw new BuilderException(MESSAGE +
                    "SearchUtilities não pode ser nulo.");
        }

        // cria busca
        org.balisunrise.swing.commons.Search search =
                new org.balisunrise.swing.commons.Search();

        // atribuições
        search.setAlias(su.alias);
        search.setEntityClass(su.entityClass);
        search.setTitle(su.title);

        // cria o EntityFilter
        EntityFilter<JPanel> ef = Application.get()
                .getVisualEntityManager()
                .getEntityFilterBuilder()
                .create(su.filterUtilities);

        // cria o EntityGrid
        EntityGrid<JPanel> eg = Application.get()
                .getVisualEntityManager()
                .getEntityGridBuilder()
                .create(su.gridUtilities);

        // Cria o Painel de Ações
        EntityActions<VisualAction,JPanel> ea = Application.get()
                .getVisualEntityManager()
                .getEntityActionBuilder()
                .create(su.entityClass,
                        su.alias);

        // Cria as Ações Visuais
        ActionProvider ap = Application.get()
                .getActionMapManager()
                .getActionProvider(su.entityClass);
        VisualAction[] vas = ap.getVisualActions(
                VisualActionTarget.SEARCH, su.alias, null);
        // adiciona as ações visuais ao painel de ações
        for (VisualAction va : vas) {
            va.setOwner(ea);
            ea.addAction(va);
        }

        // Cria o listener das ações
        EntityActionsListener eal = new EntityActionsListener();
        ea.addEntityActionsListener(eal);

        // cria as ações de um evento visual
        Action[] as = ap.getActions(EventType.VISUAL_SEARCH, su.alias, null);
        for (Action action : as) {
            action.setOwner(ea);
            eal.addVisualActinPerformedAction(action);
        }

        // cria as ações de eventos antes de confirmar
        as = ap.getActions(EventType.ENTITY_ACTION_BEFORE_CONFIRM,
                su.alias, null);
        for (Action action : as) {
            action.setOwner(ea);
            eal.addBeforeConfirmAction(action);
        }

        // cria as ações de eventos antes de cancelar
        as = ap.getActions(EventType.ENTITY_ACTION_BEFORE_CANCEL,
                su.alias, null);
        for (Action action : as) {
            action.setOwner(ea);
            eal.addBeforeCancelAction(action);
        }

        // cria entityLoader
        EntityLoader el = null;
        try{
            CommonFactory bf = Application.get().getFactory();
            EntityList list = bf.createEntityList();
            list.setOwner(search);
            el = bf.createEntityLoader(su.entityClass,list);
        }catch(FactoryException fex){
            throw new BuilderException(MESSAGE +
                    fex.getMessage(),fex);
        }

        // listener de eventos do entityLoader
        EntityLoadListener ell = new EntityLoadListener();
        el.addEntityLoadListener(ell);

        // ações de eventos de antes de carregar
        as = ap.getActions(EventType.ENTITY_FILTER_BEFORE_LOAD, su.filter, null);
        for (Action action : as) {
            action.setOwner(ef);
            ell.addBeforeLoadAction(action);
        }

        // ações de eventos de antes de iterar
        as = ap.getActions(EventType.ENTITY_FILTER_BEFORE_ITERATE,
                su.filter, null);
        for (Action action : as) {
            action.setOwner(ef);
            ell.addBeforeIterateAction(action);
        }

        // ações de eventos de depois de carregar
        as = ap.getActions(EventType.ENTITY_FILTER_AFTER_LOAD, su.filter, null);
        for (Action action : as) {
            action.setOwner(ef);
            ell.addAfterLoadAction(action);
        }

        // atribui o pai
        ef.setOwner(search);
        eg.setOwner(search);
        ea.setOwner(search);
        el.setOwner(search);

        // cria RV
        SearchPanel visualRepresentation =
                new SearchPanel(
                    ef.getVisualRepresentation(),
                    eg.getVisualRepresentation(),
                    ea.getVisualRepresentation(),
                    new SearchLayoutBuilder());

        // atribuicoes
        search.setEntityFilter(ef);
        search.setEntityGrid(eg);
        search.setEntityActions(ea);
        search.setEntityLoader(el);
        search.setVisualRepresentation(visualRepresentation);

        // nome do painel
        String name = NameUtil.buildName(search);
        search.getVisualRepresentation().setName(name);
        search.getVisualRepresentation().getAccessibleContext()
                .setAccessibleName(name);
        search.setName(name);

        return search;
    }
}
